<template>
  <div ref="main" style="width: 100%; height: 200px"></div>
</template>

<script>
import * as echarts from 'echarts/core'

export default {
  props: {
    typeChart: {
      type: String,
      default: 'bar',
    },
  },
  data() {
    return {
      dataCharts: [],
    }
  },
  mounted() {
    this.initChart()
    //初始化使用websocket
    // this.initWebsocket()
  },
  methods: {
    initChart() {
      // 基于准备好的dom，初始化echarts实例
      var myChart = echarts.init(this.$refs.main)
      // 指定图表的配置项和数据
      var option = {
        xAxis: {
          type: 'category',
          data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            data: this.dataCharts.length
              ? this.dataCharts
              : [150, 230, 224, 218, 135, 147, 260],
            type: this.typeChart,
          },
        ],
      }
      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option)
    },
    initWebsocket() {
      //客户端与服务端连接
      const ws = new WebSocket('ws://127.0.0.1:8090')
      //成功
      ws.onopen = function () {
        console.log('websocket连接成功')
      }
      //失败
      ws.onerror = function () {
        console.log('websocket连接失败')
      }
      //获取订阅者消息
      ws.onmessage = function (msg) {
        const res = mes.data
        this.dataCharts = JSON.parse(res.message)
        // this.initWebsocket()
      }
    },
  },
}
</script>

<style></style>
